<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <!-- <meta name="viewport" content="width=device-width, initial-scale=1"> -->
    <!-- The above 3 meta tags *must* come first in the head; any other head content must come *after* these tags -->
    <title>Intel IoT Commercial Developer Kit</title>
    <!-- Bootstrap -->
    <link href="css/bootstrap.min.css" rel="stylesheet">
    <!-- Custom -->
    <link href="css/main.css" rel="stylesheet">
    <link href="css/fonts.css" rel="stylesheet">
    <link rel="icon" type="image/png" sizes="32x32" href="images/favicon-32x32.png">
    <link rel="icon" type="image/png" sizes="96x96" href="images/favicon-96x96.png">
    <link rel="icon" type="image/png" sizes="16x16" href="images/favicon-16x16.png">
    <link rel="icon" type="image/x-icon" href="images/favicon.ico">
    <link rel="shortcut icon" type="image/x-icon" href="images/favicon.ico" />
    <!-- HTML5 shim and Respond.js for IE8 support of HTML5 elements and media queries -->
    <!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
    <!--[if lt IE 9]>
      <script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script>
      <script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>
    <![endif]-->
</head>

<body class="noselect">
    <!-- HOME SCREEN -->
    <nav class="home_screen navbar navbar-inverse navbar-fixed-top">
        <div class="container-fluid">
            <div class="row">
                <div class="col-xs-2">
                </div>
                <div class="col-xs-8">
                    <h1 class="navbar-title text-center">Intel IoT Commercial Developer Kit</h1>
                </div>
                <div class="col-xs-2">
                    <a class="navbar-brand navbar-right" href="#">
                        <img class="img-responsive" alt="Intel" src="images/Intel_Logo_White.png">
                    </a>
                </div>
            </div>
        </div>
    </nav>


    <!-- TRANSPORTATION USE CASE -->
    <nav class="hidden tuc_video navbar navbar-inverse navbar-fixed-top">
        <div class="container-fluid">
            <div class="row">
                <div class="col-xs-2">
                    <a class="navbar-back" href="index.html">
                        <br>
                        &lt; Home </a>
                </div>
                <div class="col-xs-8">
                    <h1 class="navbar-title text-center">Transportation Use Case</h1>
                </div>
                <div class="col-xs-2">
                    <a class="navbar-brand navbar-right" href="#">
                        <img class="img-responsive" alt="Intel" src="images/Intel_Logo_White.png">
                    </a>
                </div>
            </div>
        </div>
    </nav>
    <div class="tuc_video container-fluid container-video">
        <video poster="images/transportation_background.jpg" id="bgvid" width="100%">
            <source src="videos/Truck_Intro_R5_NoLight.mp4" type="video/mp4">
        </video>
    </div>
    <div class="hidden tuc_screen container-fluid container-transportation hidden">
        <div class="row" style="margin-top: 20px; margin-bottom: 20px;">
            <div class="col-xs-2">
                <button type="button" class="btn btn-truck-ph"><img class="img-responsive center-block" src="images/button_placeholder.png" alt=""></button>
            </div>
            <div class="col-xs-2">
                <button type="button" class="btn btn-truck-ph"><img class="img-responsive center-block" src="images/button_placeholder.png" alt=""></button>
            </div>
            <div class="col-xs-2">
                <button type="button" class="btn btn-truck-ph"><img class="img-responsive center-block" src="images/button_placeholder.png" alt=""></button>
            </div>
            <div class="col-xs-2">
                <button id="reset_btn" type="button" class="btn btn-truck"><img class="img-responsive center-block" src="images/reset_btn.png" alt="Reset"></button>
            </div>
            <div class="col-xs-2">
                <button id="viewLog" type="button" class="btn btn-truck" data-toggle="modal" data-target="#logModal"><img class="img-responsive center-block" src="images/log_btn.png" alt="View Log"></button>
            </div>
            <div class="col-xs-2">
                <button type="button" class="btn btn-truck" data-toggle="modal" data-target="#helpModal"><img class="img-responsive center-block" src="images/howto_btn.png" alt="Help"></button>
            </div>
        </div>
        <div class="row guagerow">
            <div class="col-xs-6">
                <img alt="" class="img-responsive" src="images/gauge_placeholder.png">
            </div>
            <div class="col-xs-6">
                <div class="sensor tempsensor" id="t1sensor">
                    <div class="tempheader">TEMPERATURE (<span class="fartemp selected">&#176;F</span> / <span class="celtemp">&#176;C</span>)</div>
                    <div class="tempgauge">
                      <div class="increasethreshold"><span class="glyphicon glyphicon-plus-sign" aria-hidden="true"></span></div>
                      <div class="decreasethreshold"><span class="glyphicon glyphicon-minus-sign" aria-hidden="true"></span></div>
                      <div id="main">
                          <div class="thresholdArc" id="t1_temp_threshold" class="selectedRadial noselect"></div>
                          <div class="currentArc" id="t1_temp_current" class="selectedRadial noselect"></div>
                      </div>
                    </div>
                </div>
            </div>
        </div>
        <div class="row">
            <h4 class="text-uppercase usecase_steps text-right" style="margin-right: 20px;">Use Case Steps</h4>
        </div>
        <div class="row">
            <!-- <div class="col-xs-2 col-md-4"></div> -->
            <div class="col-xs-2">
                <img alt="" src="images/step_placeholder.png" class="step_image img-responsive">
            </div>
            <div class="col-xs-2">
                <img alt="" src="images/step_placeholder.png" class="step_image img-responsive">
            </div>
            <div class="col-xs-2 hidden" id="step1i">
                <div class="btn-txt">Open Door</div>
                <img alt="step 1" src="images/step1_inactive.png" class="step_image img-responsive">
            </div>
            <div class="col-xs-2 show" id="step1a">
                <div class="btn-txt">Open Door</div>
                <img alt="step 1" src="images/step1_active.png" class="step_image img-responsive">
            </div>
            <div class="col-xs-2 show" id="step2i">
                <div class="btn-txt">Comet Temperature Sensor</div>
                <img alt="step 2" src="images/step2_inactive.png" class="step_image img-responsive">
            </div>
            <div class="col-xs-2 hidden" id="step2a">
                <div class="btn-txt">Comet Temperature Sensor</div>
                <img alt="step 2" src="images/step2_active.png" class="step_image img-responsive">
            </div>
            <div class="col-xs-2 show" id="step3i">
                <div class="btn-txt">Mute</div>
                <img alt="step 3" src="images/step3_inactive.png" class="step_image img-responsive">
            </div>
            <div class="col-xs-2 hidden" id="step3a">
                <div class="btn-txt">Mute</div>
                <img alt="step 3" src="images/step3_active.png" class="step_image img-responsive">
            </div>
            <div class="col-xs-2 show" id="step4i">
                <div class="btn-txt">Close Door</div>
                <img alt="step 4" src="images/step4_inactive.png" class="step_image img-responsive">
            </div>
            <div class="col-xs-2 hidden" id="step4a">
                <div class="btn-txt">Close Door</div>
                <img alt="step 4" src="images/step4_active.png" class="step_image img-responsive">
            </div>
        </div>
    </div>
    <!-- /container -->


    <div class="home_screen container-fluid chooser-screen">
        <div class="page-header">
            <h1>Select Use Case</h1>
            <!-- <p class="lead">Select one of the use cases to experience the experience kit with fun and easy to follow demos.</p> -->
        </div>
        <div id="carousel-use-cases" class="carousel slide" data-ride="carousel">
            <!-- Indicators -->
            <ol class="carousel-indicators">
                <li data-target="#carousel-use-cases" data-slide-to="0" class="active"></li>
                <li data-target="#carousel-use-cases" data-slide-to="1"></li>
            </ol>
            <!-- Wrapper for slides -->
            <div class="carousel-inner" role="listbox">
                <div class="item active">
                    <img class="center-block img-responsive" src="images/carousel_truck_new.png" alt="Transportation">
                    <div class="carousel-caption">
                        <h1>Transportation Use Case</h1>
                        <h4>This logistics use case demonstrates how an Intel IoT Intelligent Gateway combined with various sensors can help drive awareness and alerts of major temperature changes inside the trailer to help avoid damage to heat sensitive goods.</h4>
                        <br/>
                        <!-- <a href="transportation.html"> -->
                        <button type="button" class="btn btn-default btn-lg" id="startTransportation">Start</button>
                        <!-- </a> -->
                        <br/>
                        <br/>
                    </div>
                </div>
                <div class="item">
                    <img class="center-block img-responsive" src="images/Coming-soon_2.jpg" alt="Coming Soon">
                    <div class="carousel-caption">
                        <h1>Coming Soon</h1>
                        <h4>Watch this space for additional supported use cases.</h4>
                        <br/>
                        <br/>
                        <br/>
                        <br/>
                        <br/>
                        <!-- <button type="button" class="btn btn-default disabled">Start</button><br/><br/><br/><br/> -->
                    </div>
                </div>
            </div>
            <!-- Controls -->
            <a class="left carousel-control" href="#carousel-use-cases" role="button" data-slide="prev">
                <span class="glyphicon glyphicon-chevron-left" aria-hidden="true"></span>
                <span class="sr-only">Previous</span>
            </a>
            <a class="right carousel-control" href="#carousel-use-cases" role="button" data-slide="next">
                <span class="glyphicon glyphicon-chevron-right" aria-hidden="true"></span>
                <span class="sr-only">Next</span>
            </a>
        </div>
    </div>
    <!-- /container -->

    <!-- Modal -->
    <div class="modal fade" id="helpModal" role="dialog">
        <div class="modal-dialog modal-lg modal-truck">
            <!-- Modal content-->
            <div class="modal-content" style="background-color: rgb(236, 236, 236);">
                <div class="modal-header">
                    <button id="closebtn" type="button" class="close" data-dismiss="modal" data-toggle="tooltip" data-placement="left" data-original-title="Close">&times;</button>
                    <h4 class="modal-title">Setup Instructions</h4>
                    <p class="text-danger">
                        <br/>Warning: If you need to make any hardware changes, the device must be powered off and power source unplugged.</p>
                </div>
                <div class="modal-body">
                    <div class="completed-step hidden">
                        <p>Completed setup view:</p>
                        <img class='center-block img-responsive' src='images/help_everything.jpg'>
                    </div>
                    <div class="all-parts show">
                        <p>The following parts are required for this use case. Mouse over each part to get more information or see what the finished setup looks like. </p>
                        <p>Close to go to the use case.</p>
                        <table class="table table-condensed" style="margin-left: -10px;">
                            <tr>

                                <td class="parts-hover" id="item_galileo" data-toggle="popover" data-trigger="hover focus" title="Intel Galileo Gen 2" data-container="body" data-content="<p>As an expansion board, Base Shield v2 has many Grove connectors, making it convenient for you to use Grove products together. And it is compatible with a series of Arduino products.</p><p><strong>Instructions:</strong></p><img class='img-responsive' src='images/NUC_large_144.jpg'><br/><p>Plug the Arduino Shield into the <strong>Galileo Gen 2 pinouts</strong>.</p>" data-placement="right" data-html="true"><img class='img-responsive' src="images/NUC_trans.png" style='width:400px;'>
                                </td>

                                <td>
                                    <table>
                                    		<tr>
                                    			<td colspan="2" class="parts-hover" id="item_lcd" data-toggle="popover" data-trigger="hover focus" title="LCD RGB Backlight" data-container="body" data-content="<p>This display enables you to set the color to whatever you like. Also supports user-defined characters.</p><img class='img-responsive' src='images/popup_lcd.jpg'><br/><p><strong>Instructions:</strong></p><p>Plug into <strong>I2C</strong> in Arduino Shield.</p>" data-placement="left" data-html="true"><img class='img-responsive' src="images/item_lcd.png" style='width:100%;'></td>
                                    		</tr>
                                        <tr>
                                            <td class="parts-hover" id="item_touch" data-toggle="popover" data-trigger="hover focus" title="Touch Sensor" data-container="body" data-content="<p>It can detect the change in capacitance when a finger is near it.</p><img class='img-responsive' src='images/popup_touch.jpg'><br/><p><strong>Instructions:</strong></p><p>Plugs in to to <strong>D3</strong> of Arduino Shield.</p>" data-placement="right" data-html="true"><img class='img-responsive' src="images/item_touch.png" style='width:100%;'></td>
                                            <td class="parts-hover" id="item_button" data-toggle="popover" data-trigger="hover focus" title="Grove Button" data-container="body" data-content="<p>One independent button, configured with pull-down resistor.</p><img class='img-responsive' src='images/popup_button.jpg'><br/><p><strong>Instructions:</strong></p><p>Plugs in to <strong>D2</strong> connector of Arduino Sheild.</p>" data-placement="right" data-html="true"><img class='img-responsive' src="images/item_button.png" style='width:100%;'></td>
                                        </tr>
                                        <tr>
                                            <td class="parts-hover" id="item_led" data-toggle="popover" data-trigger="hover focus" title="LED Light" data-container="body" data-content="<p>A red LED light.</p><img class='img-responsive' src='images/popup_led.jpg'><br/><p><strong>Instructions:</strong></p><p><strong>Longer end of LED light goes into (+)</strong> and then plugs in to <strong>D4</strong> of Arduino Shield</p>" data-placement="right" data-html="true"><img class='img-responsive' src="images/item_led.png" style='width:100%;'></td>
                                            <td class="parts-hover" id="item_temperature" data-toggle="popover" data-trigger="hover focus" title="Temperature Sensor" data-container="body" data-content="<p>Uses a thermistor which returns the ambient temperature in the form of a resistance value.</p><img class='img-responsive' src='images/popup_temperature.jpg'><br/><p><strong>Instructions:</strong></p><p>Plugs in to <strong>A1</strong> of Arduino Shield.</p>" data-placement="right" data-html="true"><img class='img-responsive' src="images/item_temperature.png" style='width:100%;'></td>
                                        </tr>
                                        <tr>
                                            <td class="parts-hover" id="item_buzzer" data-toggle="popover" data-trigger="hover focus" title="Buzzer" data-container="body" data-content="<p>Will emit a tone when the output is high.</p><img class='img-responsive' src='images/popup_buzzer.jpg'><br/><p><strong>Instructions:</strong></p><p>Plugs in to to <strong>D5</strong> of Arduino Shield.</p>" data-placement="right" data-html="true"><img class='img-responsive' src="images/item_buzzer.png" style='width:100%;'></td>
                                            <td></td>
                                        </tr>
                                    </table>
                                </td>

                                <td>
                                    <table>
                                        <tr>
                                        	<td class="parts-hover" id="item_galileo" data-toggle="popover" data-trigger="hover focus" title="Intel Galileo Gen 2" data-container="body" data-content="<p>Intel Galileo Gen development board, the first in a family of Arduino certified development boards base on Intel architecture.<img class='img-responsive' src='images/Arduino_341x213.jpg'><br/></p>" data-placement="left" data-html="true"><img class='img-responsive' src="images/arduino_101.png" style='width:300px;'>
                                					</td>
                                        </tr>
                                        <tr>
                                        	<td class="parts-hover" id="item_arduino" data-toggle="popover" data-trigger="hover focus" title="Arduino Shield" data-container="body" data-content="<p>As an expansion board, Base Shield v2 has many Grove connectors, making it convenient for you to use Grove products together. And It is compatible with a series of Arduino products.</p><img class='img-responsive' src='images/popup_arduino.jpg'><br/><p><strong>Instructions:</strong></p><p>Plug the Arduino Shield into the <strong>Galileo Gen 2 pinouts</strong>.</p>" data-placement="left" data-html="true"><img class='img-responsive' src="images/item_arduino.png" style='width:300px;'>
                                        	</td>
                                        </tr>
                                    </table>

                                </td>

                            </tr>
                        </table>
                    </div>
                </div>
                <div class="modal-footer">
                    <!-- <button type="button" class="btn btn-default hidden" id="help_prev">Previous</button> -->
                    <button type="button" class="btn btn-default" id="help_next" data-target="#completedModal">View Finished Setup</button>
                </div>
            </div>
        </div>
    </div>

    <!-- Modal -->
    <div id="sensor-pop">
        <p>Pick up and hold the sensor</p>
        <div class="sensor-pop-body"></div>
    </div>
    <!-- Modal -->


    <!-- Modal -->
    <div class="modal fade" id="logModal" role="dialog">
        <div class="modal-dialog modal-lg modal-truck">
            <!-- Modal content-->
            <div class="modal-content">
                <div class="modal-header">
                    <button id="closebtn2" type="button" class="close" data-dismiss="modal" data-toggle="tooltip" data-placement="left" data-original-title="Close">&times;</button>
                    <h4 class="modal-title"><br>View Log<br></h4>
                </div>
                <div class="modal-body">
                    <div id="canvas-holder1">
                        <canvas id="chart1" style="width: 100%; height: 250px;"></canvas>
                    </div>
                    <div id="chartjs-tooltip"></div>
                    <table id="activity_log" class="table table-striped table-hover">
                        <tr>
                            <th>ALERT #</th>
                            <th>TIME</th>
                            <th>THRESHOLD (F)</th>
                            <th>TEMPERATURE (F)</th>
                            <th>STATUS</th>
                        </tr>
                        <tr class="data_row">
                            <td>1</td>
                            <td class="table_time">01-Jan-2015 11:47:28 PM</td>
                            <td class="table_temp_threshold">70</td>
                            <td class="table_temperature">65</td>
                            <td class="table_status">Button Pressed</td>
                        </tr>
                        <tr class="data_row">
                            <td>2</td>
                            <td class="table_time">01-Jan-2015 11:47:28 PM</td>
                            <td class="table_temp_threshold">70</td>
                            <td class="table_temperature">69</td>
                            <td class="table_status">Temperature Rising</td>
                        </tr>
                        <tr class="data_row">
                            <td>3</td>
                            <td class="table_time">01-Jan-2015 11:47:28 PM</td>
                            <td class="table_temp_threshold">70</td>
                            <td class="table_temperature exceeded">72</td>
                            <td class="table_status">Exceeded Threshold</td>
                        </tr>
                        <tr class="data_row">
                            <td>4</td>
                            <td class="table_time">01-Jan-2015 11:47:28 PM</td>
                            <td class="table_temp_threshold">70</td>
                            <td class="table_temperature exceeded">73</td>
                            <td class="table_status">Buzzer Stopped</td>
                        </tr>
                        <tr class="data_row">
                            <td>5</td>
                            <td class="table_time">01-Jan-2015 11:47:28 PM</td>
                            <td class="table_temp_threshold">68</td>
                            <td class="table_temperature exceeded">70.8</td>
                            <td class="table_status">Door Closed</td>
                        </tr>
                    </table>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
                </div>
               
            </div>
        </div>
         <audio id="alarm" loop>
          <source src="audio/alarm-sound.mp3" type="audio/mpeg">
        </audio>
    </div>
    <!-- jQuery (necessary for Bootstrap's JavaScript plugins) -->
    <script type="text/javascript" src="js/jquery-1.11.3.min.js"></script>
    <!-- Include all compiled plugins (below), or include individual files as needed -->
    <script src="js/bootstrap.min.js"></script>
    <script type="text/javascript" src="js/d3.min.js"></script>
    <script type="text/javascript" src="js/Chart.min.js"></script>
    <script type="text/javascript" src="js/radialProgress.js"></script>
    <script type="text/javascript" src="js/moment.min.js"></script>
    <script type="text/javascript" src="js/demo-core.js"></script>
    <script type='text/javascript'>

    $(document).ready(function() {
        console.log('1');
        $('.carousel').carousel({
            interval: false
        });

        DEMO_CORE.routes = {
            currentReadingsUrl: "/ExpKit/getData?value=current",
            logEntriesUrl: "/ExpKit/getData?value=log",
            tempThresholdUrl: "/ExpKit/threshold",
            demoStatusUrl: "/ExpKit/demo",
            updateDoorUrl: "/ExpKit/door",
            updateBuzzerUrl: "/ExpKit/buzzer",
        };
        var INITIAL_STEP_VALUE = 0;
        var INITIAL_DOOR_STATUS = false; // closed
        var INITIAL_BUZZER_STATUS = false;
        var MAX_POINTS_IN_GRAPH = 15;
        var VIDEO_DEMO_READY_TIMESTAMP = 9.5;
        var VIDEO_DOORS_FULLY_OPEN_RED_TIMESTAMP = 15;
        var VIDEO_DOORS_FULLY_OPEN_GREEN_TIMESTAMP = 17; // 13.5;
        var VIDEO_DOORS_FULLY_CLOSED_TIMESTAMP = 19.750;

        var currentStep = INITIAL_STEP_VALUE;
        var currentDoorStatus = INITIAL_DOOR_STATUS;
        var currentMuteStatus = INITIAL_BUZZER_STATUS;
        var rowTemplates = {};
        var tempDataSeries = [];
        var pauseVideoInterval = null;
        var isOverTemp = false;
        $(function() {
            $('[data-toggle="popover"]').popover();
            $('#closebtn').tooltip();
            $('#closebtn2').tooltip();
        })

        var truckbg_vid = document.getElementById("bgvid");

        if (document.location.hash === '#skip_video') {
            console.log('skip_video');
            truckbg_vid.currentTime = VIDEO_DEMO_READY_TIMESTAMP;
        }

        $('#startTransportation').on('click', function(event) {
            $('.tuc_video').removeClass("hidden");
            $('.home_screen').addClass('hidden');
            $("body").addClass('tuc_body');

            console.log('playVideo');

            // Check to see if the video has gotten to our designated pause
            // point every 100ms.
            pauseVideoInterval = setInterval(function() {
                console.log('pauseVideoInterval');
                if (truckbg_vid.currentTime >= VIDEO_DEMO_READY_TIMESTAMP) {
                    truckbg_vid.pause();
                    $('.tuc_screen').removeClass('hidden');
                    $('.container-transportation').removeClass("hidden");
                    //$('#helpModal').modal('show');

                    // drawChart();
                    refreshTemp();

                    // Start polling the feed and log APIs
                    DEMO_CORE.updateCurrentSensorReadings();
                    pollLog();

                    clearInterval(pauseVideoInterval);
                }
            }, 100);

            truckbg_vid.play();
        });

        function updateStepActivationStatus(step) {
            //currentStep = step -1;
            var showDivIds = [],
                hideDivIds = [];
            for (var i = 1; i <= 4; i++) {
                if (i != step) {
                    showDivIds.push("#step" + i + "i");
                    hideDivIds.push("#step" + i + "a");
                }
            }
            $(hideDivIds.join(', ')).removeClass('show').addClass('hidden');
            $(showDivIds.join(', ')).removeClass('hidden').addClass('show');

            $('#step' + step + 'i').removeClass('show').addClass('hidden');
            $('#step' + step + 'a').removeClass('hidden').addClass('show');
        }

        var STEP_PROGRESS = {
            // These functions update the UI for the completion of each step
            step0: function() {
                updateStepActivationStatus(1);
            },

            step1: function() {
                updateStepActivationStatus(2);
            },

            step2: function() {
                updateStepActivationStatus(3);
            },

            step3: function() {
                updateStepActivationStatus(4);
            },

        };

        function updateStep(newStep) {
            if (newStep != currentStep) {
                var stepName = 'step' + newStep;
                if (STEP_PROGRESS[stepName]) {
                    STEP_PROGRESS[stepName]();
                }
                currentStep = newStep;
            }
        }

        function updateDoor(newStatus) {
            if (newStatus !== currentDoorStatus) {
                if (newStatus) {
                    openTruckDoor();
                } else {
                    closeTruckDoor();
                }
                currentDoorStatus = newStatus;
            }
        }

        function openTruckDoor() {
            truckbg_vid.pause();
            truckbg_vid.currentTime = VIDEO_DEMO_READY_TIMESTAMP;
            truckbg_vid.play();

            setTimeout(function() {
                    truckbg_vid.pause();
                    truckbg_vid.currentTime = VIDEO_DOORS_FULLY_OPEN_RED_TIMESTAMP;
                },
                1000 * (VIDEO_DOORS_FULLY_OPEN_RED_TIMESTAMP - VIDEO_DEMO_READY_TIMESTAMP)
            );
        };

        function closeTruckDoor() {
            truckbg_vid.pause();
            truckbg_vid.currentTime = VIDEO_DOORS_FULLY_OPEN_GREEN_TIMESTAMP;
            truckbg_vid.play();

            setTimeout(function() {
                    truckbg_vid.pause();
                    truckbg_vid.currentTime = VIDEO_DOORS_FULLY_CLOSED_TIMESTAMP;
                },
                1000 * (VIDEO_DOORS_FULLY_CLOSED_TIMESTAMP - VIDEO_DOORS_FULLY_OPEN_GREEN_TIMESTAMP)
            );
        };

        // CHART

        var lineChartData = {
            labels: [],
            datasets: [{
                label: "Temperature",
                fillColor: "rgba(255,204,103,0.2)",
                strokeColor: "rgba(255,204,103,0.6)",
                pointColor: "rgba(255,204,103,0.8)",
                pointStrokeColor: "rgba(255,204,103,1.0)",
                pointHighlightFill: "#fff",
                pointHighlightStroke: "rgba(220,220,220,1)",
                data: []
            }]
        };

        function drawChart() {
            var chart = document.getElementById("chart1");
            if (window.myLine) {
                window.myLine.destroy();
                window.myLine = null;
            }

            var ctxfull = chart.getContext("2d");
            lineChartData.datasets[0].data = tempDataSeries.map(function(v) {
                return v;
            });
            lineChartData.labels = tempDataSeries.map(function(v) { return ''; });
            window.myLine = new Chart(ctxfull).Line(lineChartData, {
                responsive: true,
                maintainAspectRatio: false
            });
        }

        $('#viewLog').on('click', function() {
            setTimeout(function() {
                // fix height/width, which seem to get mangled when the
                // graph is drawn in an invisible modal....
                drawChart();
                var jChart = $(document.getElementById("chart1"));
                window.myLine.resize();
            }, 300);
        });

        $('#logModal .close').on('click', function() {
            if (window.myLine) {
                window.myLine.destroy();
                window.myLine= null;
            }
        });

        // TEMPERATURE ARC

        var t1Degree = "F";

        t1_thresholdTemp = 0;
        t1_currentTemp = 0;

        var t1_temp_threshold = d3.select(document.getElementById('t1_temp_threshold'));
        var t1_temp_current = d3.select(document.getElementById('t1_temp_current'));

        function refreshTemp() {
            if (t1Degree == "F") {
                setArcs('t1_temp_threshold', 't1_temp_current', t1_thresholdTemp, t1_currentTemp, "temp");
            } else {
                setArcs('t1_temp_threshold', 't1_temp_current', (t1_thresholdTemp - 32) * 5 / 9, (t1_currentTemp - 32) * 5 / 9, "temp");
            }
            if( t1_currentTemp >= t1_thresholdTemp && t1_thresholdTemp != 0){
                isOverTemp = true;
            } else if( t1_currentTemp < t1_thresholdTemp ){
                isOverTemp = false;
            }
            //console.log( 'refresh t', t1_currentTemp, t1_thresholdTemp );
            console.log( currentStep , 'currentStep');
        }

        function setArcs(thresholdDiv, currentDiv, thresholdValue, currentValue, arcType) {
            if (currentValue < 0) {
                currentValue = 0;
            }
            if (thresholdValue < 0) {
                thresholdValue = 0;
            }

            thresholdDiv = $('#' + thresholdDiv);
            var rp1 = radialProgress(thresholdDiv[0])
                .diameter(140)
                .minValue(0)
                .maxValue(thresholdDiv.data('maxValue') || 100)
                .value(thresholdValue)
                .render();

            currentDiv = $('#' + currentDiv);
            var rp2 = radialProgress(currentDiv[0])
                .diameter(130)
                .minValue(0)
                .maxValue(currentDiv.data('maxValue') || 100)
                .threshold(thresholdValue)
                .arctype(arcType)
                .value(currentValue)
                .render();
        }

        $('.tempheader').on('click', function() {
            var truckid = ($(this).parent().attr("id"));
            $('#' + truckid + ' .fartemp').toggleClass('selected');
            $('#' + truckid + ' .celtemp').toggleClass('selected');

            if (truckid == "t1sensor") {
                if ($('#' + truckid + ' .fartemp').hasClass('selected')) {
                    t1Degree = "F";
                    DEMO_CORE.settings.temperature_units = "Fahrenheit";
                } else {
                    t1Degree = "C";
                    DEMO_CORE.settings.temperature_units = "Celsius";
                }
            }

            refreshTemp();
        });

        $('.increasethreshold').on('click', function() {
            var sensor = $(this).closest('.tempsensor');
            var buttonid = sensor.attr("id");
            if (buttonid == "t1sensor") {
                changeThreshold(sensor, t1_thresholdTemp + 1);
            }
        });

        $('.decreasethreshold').on('click', function() {
            var sensor = $(this).closest('.tempsensor');
            var buttonid = sensor.attr("id");
            if (buttonid == "t1sensor") {
                changeThreshold(sensor, t1_thresholdTemp - 1);
            }
        });

        function changeThreshold(whichThreshold, newValue) {
            if (newValue < 0) {
                newValue = 0;
            }
            if (newValue > 90) {
                newValue = 90;
            }
            var updateValue = newValue;
            var url = DEMO_CORE.buildServerUrl(
                DEMO_CORE.routes.tempThresholdUrl);
            url += "?value=" + encodeURIComponent(newValue.toString());
            $.ajax(url, {
                dataType: 'json',
                type: DEMO_CORE.defaultHttpMethod,
                cache: DEMO_CORE.allowCaching,
            }).
            done(function(data, textStatus, jqXhr) {
                updateValue = parseInt(data[0].threshold, 10);
            }).
            always(function() {
                switch (whichThreshold.attr('id')) {
                    case "t1sensor":
                        t1_thresholdTemp = updateValue;
                        refreshTemp();
                        break;
                }
            });
        }

        // Help Modal

        $('#help_next').on('click', function() {
            $('.completed-step').toggleClass('hidden');
            $('.completed-step').toggleClass('show');

            $('.all-parts').toggleClass('show');
            $('.all-parts').toggleClass('hidden');

            if ($(this).text() == 'View All Parts') {
                $(this).text('View Finished Setup');
            } else {
                $(this).text('View All Parts');
            }
        })


        // RESET FUNCTION

        $('#reset_btn').on('click', function() {
            resetDemoStatus();
            resetUseCase();
        })

        function resetUseCase() {
            truckbg_vid.pause();
            truckbg_vid.currentTime = 9.5;

            updateStepActivationStatus(1);

            t1Degree = "F";

            t1_thresholdTemp = 0;
            t1_currentTemp = 0;

            refreshTemp();
        }

        function initializeDemoStatus() {
            console.log('initializeDemoStatus');
            resetDemoStatus();
            DEMO_CORE.shouldPollSensors = true;
            var activityLog = $('#activity_log');
            rowTemplates[activityLog.attr('id')] = activityLog.
            find('tr.data_row').first().clone();
        }

        function resetDemoStatus() {
            $.ajax(DEMO_CORE.buildServerUrl('/ExpKit/getData?value=reset'), {
                dataType: 'text',
                type: DEMO_CORE.defaultHttpMethod,
                cache: DEMO_CORE.allowCaching,
            }).
            done(function(data, textStatus, jqXhr) {
                console.log("Demo Reset Status: " + data);

                currentStep = INITIAL_STEP_VALUE;
                updateStep(currentStep);

                currentDoorStatus = INITIAL_DOOR_STATUS;
                updateDoor(currentDoorStatus);
            }).
            fail(function(jqXhr, textStatus, errorThrown) {
                console.log("initializeDemoStatus error " + textStatus + ": ", errorThrown);
            });
        }

        function updateTempGraphData(newData, maxSize) {
            var points;
            var value = DEMO_CORE.fahrenheitTempToPreferredUnit(newData.temperature);
            var label = '';
            // newData.timestamp.format(DEMO_CORE.getHourFormat(true));

            tempDataSeries.push(value);
            if (tempDataSeries.length > maxSize) {
                tempDataSeries.splice(0, tempDataSeries.length - (maxSize - 1));
            }

            if (window.myLine) {
                points = window.myLine.datasets[0].points;
                if (points.length >= maxSize) {
                    window.myLine.removeData();
                }
                window.myLine.addData([value], label);
                window.myLine.update();
            }
        }

        function formatFeedData(data) {
            return {
                timestamp: DEMO_CORE.parseTimestamp(
                    DEMO_CORE.fixupTimestamp(data.timestamp)),
                temperature: parseFloat(data.temp),
                threshold: parseInt(data.threshold, 10),
                door_status: DEMO_CORE.isTruthy(data.door_status),
                demo_status: DEMO_CORE.isTruthy(data.demo_status),
                demo_step: parseInt(data.current_step, 10),
            };
        }

        function formatLogData(entry) {
            return {
                timestamp: DEMO_CORE.parseTimestamp(
                    DEMO_CORE.fixupTimestamp(entry.timestamp)),
                temperature: parseFloat(entry.temp),
                threshold: parseFloat(entry.threshold),
                status: entry.event
            };
        };

        function formatLogEntries(logEntries) {
            return $.map(logEntries, formatLogData);
        }

        function updateLogTable(logTable, logEntries) {
            var rows = logTable.find('tr.data_row');

            while (logEntries.length > rows.length) {
                var templateRow = rowTemplates[logTable.attr('id')];
                logTable.find('tbody').append(templateRow.clone());
                rows = logTable.find('tr.data_row');
            }
            if (logEntries.length < rows.length) {
                rows.slice(logEntries.length).remove();
            }

            rows.each(function(index, row) {
                var entry = logEntries[index];
                var cells = $(row).find('td');
                if (entry) {
                    cells.first().parent().css('display', 'table-row');
                    cells.first().html(index + 1);
                    cells.filter('.table_time').html(
                        DEMO_CORE.formatDateTime(entry.timestamp));
                    var displayThreshold = DEMO_CORE.fahrenheitTempToPreferredUnit(entry.threshold, 1);
                    var displayTemp = DEMO_CORE.fahrenheitTempToPreferredUnit(entry.temperature, 1);
                    var highlight = entry.temperature >= entry.threshold;
                    cells.filter('.table_temp_threshold').
                    html(displayThreshold).
                    toggleClass('exceeded', highlight);
                    cells.filter('.table_temperature').
                    html(displayTemp).
                    toggleClass('exceeded', highlight);
                    cells.filter('.table_status').
                    html(entry.status).
                    toggleClass('exceeded', highlight);
                } else {
                    cells.first().parent().css('display', 'none');
                }
            });
        }

        function setDoorStatus(truthy_for_open) {
            var doorStatus = '0';
            if (truthy_for_open) {
                doorStatus = '1';
            }

            var url = DEMO_CORE.routes.updateDoorUrl + "?value=" + doorStatus;
            $.ajax(DEMO_CORE.buildServerUrl(url), {
                dataType: 'text',
                type: DEMO_CORE.defaultHttpMethod,
                cache: DEMO_CORE.allowCaching,
            }).
            done(function(data, textStatus, jqXhr) {
                var newDoorStatus = false;
                console.log("Door Status: " + data);

                if (parseInt(data, 10) == 1){
                    newDoorStatus = true;
                }
                updateDoor(newDoorStatus);
            }).
            fail(function(jqXhr, textStatus, errorThrown) {
                console.log("setDoorStatus error " + textStatus + ": ", errorThrown);
            });
        }

        function setMuteStatus(truthy_for_on) {
            var buzzerStatus = 'off';
            if (truthy_for_on) {
                buzzerStatus = 'on';
            }

            var url = DEMO_CORE.routes.updateBuzzerUrl + "?value=" + buzzerStatus;
            $.ajax(DEMO_CORE.buildServerUrl(url), {
                dataType: 'json',
                type: DEMO_CORE.defaultHttpMethod,
                cache: DEMO_CORE.allowCaching,
            }).
            done(function(data, textStatus, jqXhr) {
                if (data.buzzer_status === 'on') {
                    currentBuzzerStatus = true;
                } else {
                    currentBuzzerStatus = false;
                }

                console.log("Buzzer Status: " + currentBuzzerStatus + " (" + data + ")");
            }).
            fail(function(jqXhr, textStatus, errorThrown) {
                console.log("setBuzzerStatus error " + textStatus + ": ", errorThrown);
            });
        }

        function pollLog() {
            if (DEMO_CORE.shouldPollSensors) {
                $.ajax(DEMO_CORE.buildServerUrl(DEMO_CORE.routes.logEntriesUrl), {
                    dataType: 'json',
                    type: DEMO_CORE.defaultHttpMethod,
                    cache: DEMO_CORE.allowCaching,
                }).
                done(function(data, textStatus, jqXhr) {
                    var logEntries = formatLogEntries(data);
                    updateLogTable($('#activity_log'), logEntries);
                }).
                fail(function(jqXhr, textStatus, errorThrown) {
                    console.log("error " + textStatus + ": ", errorThrown);
                }).
                always(function() {
                    // Schedule poll only after AJAX call finishes
                    DEMO_CORE.scheduleNextPoll(pollLog);
                });
            } else {
                // Set timer for next check
                DEMO_CORE.scheduleNextPoll(pollLog);
            }
        };

        $(document).on('DEMO_CORE.sensors.current', function(event, data) {
            data = formatFeedData(data[0]);

            // console.log("Current Sensor Readings: ", data);

            t1_currentTemp = data.temperature;
            t1_thresholdTemp = data.threshold;

            refreshTemp();
            updateStep(data.demo_step - 1);
            updateDoor(data.door_status);

            updateTempGraphData(data, MAX_POINTS_IN_GRAPH);
        });

        /*AUDIO FUNCTIONALITY*/
        var alarmPlaying = false;
        function playAlarm(){
            $('#alarm')[0].play();
        }
        function stopAlarm(){
            $('#alarm')[0].pause();
            $('#alarm')[0].currentTime = 0;
        }

        //isOverTemp is true and currentMuteStatus is false
        window.setInterval(function(){
            console.log( currentStep );
            if( isOverTemp && !alarmPlaying && !currentMuteStatus && currentStep == 1){
                playAlarm();
                alarmPlaying = true;
                updateStepActivationStatus(3);
            } else if ( !isOverTemp && !currentMuteStatus ){
                alarmPlaying = false;
                stopAlarm();
            } else if( currentMuteStatus ){
                alarmPlaying = false;
                stopAlarm();
            }
            console.log( isOverTemp, alarmPlaying, currentMuteStatus)
        }, 100);

        /*NEW DELL FUNCTIONALITY ERHAN ERGENEKAN*/
        $('#step1a').on("click", function(){
            setDoorStatus(true);
            updateStepActivationStatus(2);
        });
        $('#step2a').on('mouseover', function(){
            $('#sensor-pop').stop().fadeIn();

        })
        $('#step2a').on('mouseout', function(){
            $('#sensor-pop').stop().fadeOut();

        })
        $('#step2a').on("click", function(){
            // updateStepActivationStatus(3);
        });
        $('#step3a').on("click", function(){
            /*setBuzzerStatus(false);*/
            currentMuteStatus = true;
            updateStepActivationStatus(4);
        });
        $('#step4a').on("click", function(){
            setDoorStatus(false);
            currentMuteStatus = false;
            updateStepActivationStatus(1);
        });
        initializeDemoStatus();
    });
    </script>
</body>

</html>
